package com.wangtianxiang.rabbitmq.processor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;

import java.util.Arrays;


public abstract class BeanRegister {

    private static final Logger logger = LoggerFactory.getLogger(BeanRegister.class);

    public BeanDefinitionHolder registerBean(BeanDefinitionRegistry registry, BeanNameGenerator beanNameGenerator, String name, String[] alias,
                             AnnotatedBeanDefinition annotatedBeanDefinition){
        BeanDefinitionHolder beanDefinitionHolder = null;
        Exception exception = null;
        try{
            // 可以自动生成name
            String beanName = (null != name ? name : beanNameGenerator.generateBeanName(annotatedBeanDefinition, registry));
            // bean注册的holer类.
            beanDefinitionHolder = new BeanDefinitionHolder(annotatedBeanDefinition, beanName, alias);
            // 使用bean注册工具类进行注册.
            BeanDefinitionReaderUtils.registerBeanDefinition(beanDefinitionHolder, registry);
        }catch (Exception e){
            exception = e;
            throw e;
        }finally {
            logger.info("###### registration for bean[{}] is success?{}, beanClassName[{}], beanAlias[{}].",(exception==null?"true": "false, error: "+ exception.getMessage()), name,annotatedBeanDefinition.getBeanClassName(), Arrays.toString(alias));
        }

        return beanDefinitionHolder;

    }
}
